"""
打包脚本 - 将闹钟程序打包成Windows可执行文件
使用PyInstaller进行打包
"""
import os
import sys
import subprocess
import shutil


def check_pyinstaller():
    """检查PyInstaller是否已安装"""
    try:
        import PyInstaller
        return True
    except ImportError:
        return False


def install_pyinstaller():
    """安装PyInstaller"""
    print("正在安装PyInstaller...")
    try:
        subprocess.check_call([sys.executable, "-m", "pip", "install", "pyinstaller"])
        print("✅ PyInstaller安装成功")
        return True
    except subprocess.CalledProcessError:
        print("❌ PyInstaller安装失败")
        return False


def build_exe():
    """打包程序为EXE"""
    print("\n" + "="*60)
    print("开始打包闹钟程序...")
    print("="*60 + "\n")
    
    # 检查main.py是否存在
    if not os.path.exists("main.py"):
        print("❌ 错误: 找不到main.py文件")
        return False
    
    # PyInstaller命令参数
    cmd = [
        "pyinstaller",
        "--name=闹钟程序",           # 程序名称
        "--windowed",                # 无控制台窗口
        "--onedir",                  # 打包成一个文件夹
        "--icon=NONE",               # 图标（如果有的话）
        "--add-data=ringtones;ringtones",  # 包含铃声文件夹
        "--hidden-import=pygame",    # 确保包含pygame
        "--hidden-import=pycaw",     # 确保包含pycaw
        "--hidden-import=comtypes",  # 确保包含comtypes
        "--clean",                   # 清理临时文件
        "main.py"
    ]
    
    print("📦 执行打包命令...")
    print(f"命令: {' '.join(cmd)}\n")
    
    try:
        # 执行打包
        result = subprocess.run(cmd, check=True, capture_output=True, text=True)
        
        print("\n" + "="*60)
        print("✅ 打包成功！")
        print("="*60)
        
        # 显示输出位置
        dist_path = os.path.join(os.getcwd(), "dist", "闹钟程序")
        print(f"\n📁 可执行文件位置: {dist_path}")
        print(f"🚀 运行程序: {os.path.join(dist_path, '闹钟程序.exe')}")
        
        # 复制ringtones文件夹（如果存在）
        if os.path.exists("ringtones"):
            dest_ringtones = os.path.join(dist_path, "ringtones")
            if os.path.exists(dest_ringtones):
                shutil.rmtree(dest_ringtones)
            shutil.copytree("ringtones", dest_ringtones)
            print(f"✅ 已复制铃声文件夹到: {dest_ringtones}")
        
        print("\n" + "="*60)
        print("打包完成！您可以将整个文件夹分发给其他用户。")
        print("="*60 + "\n")
        
        return True
        
    except subprocess.CalledProcessError as e:
        print("\n" + "="*60)
        print("❌ 打包失败")
        print("="*60)
        print(f"\n错误信息:\n{e.stderr}")
        return False


def clean_build_files():
    """清理构建文件"""
    print("\n是否清理构建临时文件？(y/n): ", end="")
    choice = input().strip().lower()
    
    if choice == 'y':
        dirs_to_remove = ["build", "__pycache__"]
        files_to_remove = ["闹钟程序.spec"]
        
        for dir_name in dirs_to_remove:
            if os.path.exists(dir_name):
                shutil.rmtree(dir_name)
                print(f"✅ 已删除: {dir_name}")
        
        for file_name in files_to_remove:
            if os.path.exists(file_name):
                os.remove(file_name)
                print(f"✅ 已删除: {file_name}")
        
        print("\n清理完成！")


def main():
    """主函数"""
    print("\n" + "="*60)
    print("闹钟程序 - EXE打包工具")
    print("="*60 + "\n")
    
    # 检查PyInstaller
    if not check_pyinstaller():
        print("⚠️  未检测到PyInstaller")
        print("是否现在安装？(y/n): ", end="")
        choice = input().strip().lower()
        
        if choice == 'y':
            if not install_pyinstaller():
                print("\n请手动安装PyInstaller: pip install pyinstaller")
                input("\n按回车键退出...")
                return
        else:
            print("\n请先安装PyInstaller: pip install pyinstaller")
            input("\n按回车键退出...")
            return
    
    # 执行打包
    success = build_exe()
    
    if success:
        # 询问是否清理临时文件
        clean_build_files()
    
    input("\n按回车键退出...")


if __name__ == "__main__":
    main()
